package redis_controller

import (
	"go-redis-demo/database/redis"
	"go-redis-demo/dto"
	"net/http"

	"github.com/gin-gonic/gin"
)

func RedisSet(c *gin.Context) {
	var param dto.RedisParam
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}
	success := redis.SetKey(param.Key, param.Value, param.Exp)
	if success {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "success",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": "fail",
		})
	}
}

func RedisGet(c *gin.Context) {
	var param dto.RedisParam
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}
	value := redis.GetKey(param.Key)
	if value == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    404,
			"message": "not found",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "success",
			"value":   value,
		})
	}
}

func RedisHashSet(c *gin.Context) {
	var param dto.RedisHashParam
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}
	success := redis.HSet(param.Item, param.Key, param.Value)
	if success {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "success",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    500,
			"message": "fail",
		})
	}
}

func RedisHashGet(c *gin.Context) {
	var param dto.RedisHashParam
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}
	value := redis.HGet(param.Item, param.Key)
	if value == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    404,
			"message": "not found",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "success",
			"value":   value,
		})
	}
}
